package com.yunc.base.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;

/**
 * 使用方式
 * @PreAuthorize("hasPermission(null, 'sys:job:save')")
 *
 * @author congcong tao
 * @create 2020-01-08 23:19
 */
@Configuration
public class MyPermissionEvaluator implements PermissionEvaluator {

    /**
     * targetDomainObject，第一个参数，可以放链接或者其他信息
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        boolean accessable = false;
        if (authentication.getPrincipal().toString().compareToIgnoreCase("anonymousUser") != 0) {
            String privilege = (String) permission;
            for (GrantedAuthority authority : authentication.getAuthorities()){
                if(privilege.equalsIgnoreCase(authority.getAuthority())){
                    accessable = true;
                    break;
                }
            }
            return accessable;
        }
        return accessable;
    }

    /**
     * 用于ACL的访问控制
     */
    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        // TODO Auto-generated method stub
        return false;
    }
}
